package cn.mengfly.fxtest.app;

import cn.mengfly.fxtest.util.UiUtil;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import lombok.Data;

/**
 * @author Mengfly
 * @date 2021/5/27 22:27
 */
public class TableSelectApp extends Application {

    @Data
    public static class Item {

        private final String sku;
        private final String descr;
        private final Float price;
        private final Boolean taxable;

        public Item(String sku, String descr, Float price, Boolean taxable) {
            this.sku = sku;
            this.descr = descr;
            this.price = price;
            this.taxable = taxable;
        }
    }

    @Override
    public void start(Stage primaryStage) {
        TableView<Item> tblItems = new TableView<>();
        tblItems.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        VBox.setVgrow(tblItems, Priority.ALWAYS);

        UiUtil.initTable(tblItems, Item.class);

        tblItems.getItems().addAll(
                new Item("KBD-0455892", "Mechanical Keyboard", 100.0f, true),
                new Item("145256", "Product Docs", 0.0f, false),
                new Item("OR-198975", "O-Ring (100)", 10.0f, true)
        );

        Button btnInventory = new Button("Inventory");
        Button btnCalcTax = new Button("Tax");
        Button btnClear = new Button("Clear");
        btnClear.setOnAction(event -> tblItems.getSelectionModel().clearSelection());

        btnInventory.disableProperty().bind(
                tblItems.getSelectionModel().selectedItemProperty().isNull()
        );

        btnCalcTax.disableProperty().bind(
                tblItems.getSelectionModel().selectedItemProperty().isNull().or(
                        Bindings.select(
                                tblItems.getSelectionModel().selectedItemProperty(),
                                "taxable"
                        ).isEqualTo(false)
                )
        );

        HBox hBox = new HBox();
        hBox.getChildren().addAll(btnInventory, btnCalcTax, btnClear);
        hBox.setSpacing(10);

        VBox vBox = new VBox();
        vBox.setAlignment(Pos.CENTER);
        vBox.setPadding(new Insets(10));
        vBox.getChildren().addAll(tblItems, hBox);
        vBox.setSpacing(10);

        Scene scene = new Scene(vBox);

        primaryStage.setScene(scene);
        primaryStage.setTitle("TableSelectApp");
        primaryStage.show();
    }




}
